<?php

//给指定模版添加自定义字段
function add_custom_fields_to_template_pages()
{
    // 定义模板名称和需要添加的自定义字段
    $template_pages = array(
        'template-one.php' => array(
            'custom_field_one',
            'custom_field_two'
        ),
        'template-two.php' => array(
            'custom_field_three',
            'custom_field_four'
        )
        // 添加更多的模板名称和自定义字段
    );

    foreach ($template_pages as $template => $fields) {
        $args = array(
            'post_type'      => 'page',
            'post_status'    => 'any',
            'posts_per_page' => -1,
            'meta_key'       => '_wp_page_template',
            'meta_value'     => $template
        );

        $pages = get_posts($args);

        foreach ($pages as $page) {
            foreach ($fields as $field) {
                add_post_meta($page->ID, $field, '', true);
            }
        }
    }
}
add_action('init', 'add_custom_fields_to_template_pages');


// 页面模版中获取自定义字段的值
//$custom_field_one = get_post_meta(get_the_ID(), 'custom_field_one', true);
//$custom_field_two = get_post_meta(get_the_ID(), 'custom_field_two', true);
//
//// 使用自定义字段的值
//echo '<p>Custom Field One: ' . $custom_field_one . '</p>';
//echo '<p>Custom Field Two: ' . $custom_field_two . '</p>';